﻿module Sustainalytics.Governance {

    import Common = Sustainalytics.Common;
    import Company = Sustainalytics.Company;
    import LRTM = Sustainalytics.LRTM;
    import Research = Sustainalytics.Research;

    export class GovernanceProfileController extends Research.ResearchPageController {

        // whether current view is still loading
        public isInitLoading: boolean;

        // employee in charge with respective industry
        public companyGovernanceProfile: GovernanceProfileDto;
        
        public notFoundMessage: string;
        public noClaims: boolean;
        public viewName:string;
        public $routeParams: any;

        private userId: string;
        private accountId: string;

        public issueSelect: IndicatorDataDto;
        public selectedIssueAnchor: string;

        constructor(
            private $rootScope: ng.IScope,
            protected $scope: Company.ICompanyBasedScope,
            protected $q: ng.IQService,
            protected $sce: ng.ISCEService,
            protected $timeout: ng.ITimeoutService,
            protected $location: ng.ILocationService,
            protected RoutingService: Routing.IRoutingService,
            protected CompanyService: Company.ICompanyService,
            protected GovernanceProfileService: GovernanceProfileService,
            protected LongRunningTaskManagerService: LRTM.LongRunningTaskManagerService) {

            super($scope, $q, $location, RoutingService, CompanyService);

            var ctx = this;
            ctx.$routeParams = ctx.RoutingService.getRouteParams();
            ctx.$scope['governancectrl'] = ctx;

            ctx.userId = ctx.$rootScope['userInfo'].userId;
            ctx.accountId = ctx.$rootScope['userInfo'].accountId;

            ctx.init();
        }

        // init logic
        private init(): ng.IPromise<any> {
            var ctx = this;

            ctx.viewName = ctx.getViewNames().Summary;
            ctx.isInitLoading = true;

            var def = ctx.$q.defer();

            var initPromise = super.initPage();
            ctx.$rootScope['loading'] = true;
            // set EsgSummary view as the default view
            initPromise.then(
                // success
                function () {
                    ctx.$timeout(function () {
                        ctx.$scope.$apply(function () {

                            // get industry lead personnel
                            ctx.getCompanyGovernanceProfile().then(
                                // success
                                function () {
                                    def.resolve();
                                },
                                // error
                                function () {
                                    def.reject();
                                });
                        });
                    });
                },
                // error
                function (reason) {
                    def.reject(reason);
                });

            var promise = def.promise;

            promise['finally'](function () {
                ctx.isInitLoading = false;
                ctx.$rootScope['loading'] = false;
                if (ctx.company != undefined) {
                    ga('create', 'UA-4379897-6', {
                        'userId': ctx.userId,
                        'cookieDomain': 'none',
                        'name': 'globalAccess'
                    });

                    ga('globalAccess.set', 'dimension1', ctx.userId);

                    var dateNow = new Date();
                    var dateNowString = [dateNow.getDate(), dateNow.getMonth() + 1, dateNow.getFullYear()].join("/");
                    var gaObject: any = {
                        Date: dateNowString,
                        AccountId: ctx.accountId,
                        UserId: ctx.userId,
                        CompanyId: ctx.company.id
                    };

                    ga('globalAccess.send', {
                        'hitType': 'event',
                        'eventCategory': 'Research',
                        'eventAction': 'OnscreenCorporateGovernanceReport',
                        'eventLabel': JSON.stringify(gaObject)
                    });
                }
            });

            return promise;
        }

        // init - get company governance profile
        private getCompanyGovernanceProfile(): ng.IPromise<GovernanceProfileDto> {
            var ctx = this;

            var promise = ctx.GovernanceProfileService.getGovernanceProfile(ctx.company.id);

            promise.then(function (res: any) //GovernanceProfileDto or 7000 or 7001
            {
                if (res.errCode != undefined)
                {
                    ctx.notFoundMessage = res.message;
                }
                else
                {
                    ctx.$timeout(function () {
                        ctx.$scope.$apply(function () {
                            ctx.companyGovernanceProfile = res;
                            ctx.changeView(Sustainalytics.Governance.GovernanceViewNames.Summary);
                        });
                    });   
                }
            },
                (reason) =>
                {
                    if (reason.status == 401)
                    {
                        ctx.noClaims = true;
                    }
                });

            return promise;
        }


        public DownloadGovernancePDF(fileId: string, fileName: string, fileType: string) {
            var ctx = this;
            var taskNumber = 202;
            var data = { fileId: fileId, fileName: fileName, fileType: fileType };

            var fileNameDownload = "";

            if (fileType == "report")
                fileNameDownload = ctx.company.companyName + "_CG" + ctx.companyGovernanceProfile.reportType + "_" + moment().format("DDMMYYYY") + ".pdf";
            else
                fileNameDownload = fileName;

            var promise = ctx.LongRunningTaskManagerService.runTask(fileNameDownload, JSON.stringify(data), taskNumber, true, null);
            
            ga('create', 'UA-4379897-6', {
                'userId': ctx.userId, 'cookieDomain': 'none', 'name': 'globalAccess'
            });

            ga('globalAccess.set', 'dimension1', ctx.userId);

            var dateNow = new Date();
            var dateNowString = [dateNow.getDate(), dateNow.getMonth() + 1, dateNow.getFullYear()].join("/");
            var gaObject: any = {
                Date: dateNowString,
                AccountId: ctx.accountId,
                UserId: ctx.userId,
                CompanyId: ctx.company.id
            };

            ga('globalAccess.send', {
                'hitType': 'event', 'eventCategory': 'Research', 'eventAction': 'PDFCorporateGovernanceReport', 'eventLabel': JSON.stringify(gaObject)
            });

        }


        public changeView(viewName: string): void {
            var ctx = this;

            ctx.$location.hash("");

            if (viewName) {
                ctx.viewName = viewName;
            }

            ga('create', 'UA-4379897-6', {
                'userId': ctx.userId, 'cookieDomain': 'none', 'name': 'globalAccess'
            });

            ga('globalAccess.set', 'dimension1', ctx.userId);

            ga('globalAccess.send', {
                'hitType': 'event', 'eventCategory': 'Onscreen-Report', 'eventAction': 'Controversies - ESG Tabs', 'eventLabel': viewName
            });

        }

        public getViewNames(): any {
            return GovernanceViewNames;
        }

        
        public DownloadGovernanceFileEnabled(fileId: string, fileName: string): boolean {
            var ctx = this;
            var result = false;

            if (fileId != undefined && fileName != undefined) {
                result = true;
            }

            return result;
        }


        //public RenderHTML(htmlCode: string) {
        //    var ctx = this;
        //    return ctx.$sce.trustAsHtml(htmlCode);
        //}

    }

    angular.module(governanceModuleName).controller('GovernanceProfileController', ['$rootScope', '$scope', '$q', '$sce', '$timeout', '$location', 'RoutingService', 'CompanyService', 'GovernanceProfileService','LongRunningTaskManagerService', GovernanceProfileController]);

} 